-module(fun_httpc_request).
-include("common.hrl").
-export([send_to_background/2,send_to_background/5,data_call_back/2,default_call_back/2]).

send_to_background(Req,Args,Mod,Fun,CallArgs)->
	case db:get_config(addrbc) of
		"0.0.0.0" -> skip;
		_ ->
			Url=make_url(Req, Args),
			?debug("URL_CALLBACK:~p",[Url]),
			fun_http_client:async_http_request(get, {Url,[]}, {Mod, Fun, CallArgs})
	end.
send_to_background(Req,Args)->
	?log_trace("send_to_background,{Req,Args} = ~p",[{Req,Args}]),
	case db:get_config(addrbc) of
		"0.0.0.0" -> skip;
		_ ->
			Url=make_url(Req, Args),
			?log_trace("send_to_background,Url = ~p",[Url]),
			%% 	?debug("URL_NO_CALLBACK:~p",[Url]),
			httpc:request(get, {Url,[]}, [], [{sync, false}, {receiver,self()}])
	end.


make_url(get_cdkey_info,{Key})->
	Addr=db:get_config(addrbc),
	"http://"++Addr++"/game_gm/cdkeyInterface/queryCdkey"++
		"?cdkey="++util:to_list(Key);

make_url(reported_ply_num,PlyNum)->
	Addr=db:get_config(addrbc),
	"http://"++Addr++"/game_gm/reported_ply_num"++
		"?ply_num="++util:to_list(PlyNum);

make_url(_,_) -> "".




default_call_back(_,_)->ok.		

data_call_back({StatusLine, Body}, {get_cdkey_info,Hid})->
	?debug("!!!!!!!!!!!!!!!!!!!!!!!!!~p",[{StatusLine, Body}]),
	case  rfc4627:decode(Body)  of  
		{ok, {obj, Datas}, []} when  erlang:is_list(Datas) andalso length(Datas)==3->
			%% 				[{"status",<<"ok">>},{"type",Type},{"key",Key}]
			case lists:keyfind("status", 1, Datas)  of  
				{_,<<"ok">>}->
					{_,Type}=lists:keyfind("type", 1, Datas),
					{_,Key}=lists:keyfind("key", 1, Datas),
					gen_server:cast(Hid, {get_cdkey_info,{ok,util:to_list(Type),util:to_list(Key)}});
				_->gen_server:cast(Hid, {get_cdkey_info,{nokey}})
			end;
		_R-> 
			?debug("call_back_error~p",[_R]),
			gen_server:cast(Hid, {get_cdkey_info,{nokey}})
	end;
data_call_back(_, _)->ok.